<template>
  <Menu v-if="menuList" ref="left_menu" :active-name="menu.activeName" theme="light" width="auto"
    :open-names="menu.openNames" :style="{ minHeight: '100vh' }" :accordion="true" @on-select="onLeftSelect">
    <MenuItem name="index2">
    <Icon type="md-home"></Icon>
    首页
    </MenuItem>
    <span v-for="v in menuList" :key="v.id">
      <Submenu v-if="typeof v.sub != 'undefined'" :name="'menu' + v.id">
        <template #title>
          <Icon v-if="v.icon" :type="v.icon"></Icon>
          {{ v.title }}
        </template>
        <MenuItem v-for="v1 in v.sub" :key="v1.id" :name="v1.url.replace(/\//, '_')">
        <Icon v-if="v1.icon" :type="v1.icon"></Icon>
        {{ v1.title }}
        </MenuItem>
      </Submenu>
      <MenuItem v-else :name="v.url == '#' ? 'menu' + v.id : v.url.replace(/\//, '_')">
      <Icon v-if="v.icon" :type="v.icon"></Icon>
      {{ v.title }}
      </MenuItem>
    </span>
  </Menu>
</template>
<script>
import { Menu, MenuItem, Submenu, Icon } from 'view-ui-plus';
export default {
  comments: [
    Menu,
    MenuItem,
    Submenu,
    Icon
  ],
  data() {
    return {
      menuList: [],
      menu: {
        activeName: 'index2',
        openNames: []
      }
    }
  },
  created() {
    let token = localStorage.getItem('token'), fullPath = this.$route.path, menu = localStorage.getItem('menu');
    if (token) {
      this.$submit('/admin/login/isLogin', {}, res => {
        if (res.data.status == '10000') {
          if (fullPath == '/admin/login') {
            this.$jumpUrl({ path: '/admin/index' });
          }
        } else {
          localStorage.clear();
          if (fullPath != '/admin/login') this.$router.push({ path: '/admin/login' }).catch(() => { });
        }
      })
    } else if (fullPath != '/admin/login') {
      this.$router.push({ path: '/admin/login' }).catch(() => { });
    }
    if (!menu) {
      localStorage.clear();
      this.$router.push({ path: '/admin/login' }).catch(() => { });
    } else {
      this.menuList = JSON.parse(menu);
    }
  },
  methods: {
    onLeftSelect(name) {
      try {
        if (name == 'index2') {
          this.$router.push({ path: '/admin' }).catch(() => { });
        } else if (!/^menu\d+/.test(name)) {
          this.$router.push({ path: '/admin/' + name.replace(/\_/g, '/') }).catch(() => { });
        }
        this.menu.activeName = name;
        let temp = JSON.parse(localStorage.getItem('menu1'));
        this.menu.openNames = [temp[name]];
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss">
.top {
  span {
    color: #fff;
    font-size: 2rem;
  }
}
.ivu-menu-item,.ivu-menu-submenu-title{
  text-align: left;
}
</style>